package com.joysuch.wwyt.workflow.engine;


import lombok.extern.slf4j.Slf4j;

import org.activiti.bpmn.model.Process;
import org.activiti.engine.ActivitiEngineAgenda;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ExecutionEntityManager;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntityManager;
import org.activiti.engine.impl.util.ProcessDefinitionUtil;

import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

/**
 * 业务流程引擎 创建指定任务节点 接口
 */


@Slf4j
public class JumpTaskCommand implements Command<Object> {

    /**
     * 当前TaskId
     */
    private String curTaskId;

    /**
     * 目标流程定义节点
     */
    private String targetFlowId;

    private Map<String, Object> varMap;

    public JumpTaskCommand(String curTaskId, String targetFlowId, Map<String, Object> varMap ){
       this.curTaskId = curTaskId;
       this.targetFlowId = targetFlowId;
       this.varMap = varMap;
   }


    @Override
    public Object execute(CommandContext commandContext) {
        ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager();
        TaskEntityManager taskEntityManager = commandContext.getTaskEntityManager();
        TaskEntity taskEntity = taskEntityManager.findById(this.curTaskId);
        ExecutionEntity executionEntity = executionEntityManager.findById(taskEntity.getExecutionId());

         Process process = ProcessDefinitionUtil.getProcess(executionEntity.getProcessDefinitionId());

        taskEntityManager.deleteTask(taskEntity, "移动节点", true, true);

        executionEntity.setCurrentFlowElement(process.getFlowElement(targetFlowId));
        executionEntity.setVariablesLocal(varMap);

        ActivitiEngineAgenda agenda = commandContext.getAgenda();
        agenda.planContinueProcessInCompensation(executionEntity);
        return null;
    }
}




